/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var defaultMessage = "Please correction your input fill before sign up!";

var LoginPopup = {

    isCreate: false,

    init: function () {
        this.show();
        this.initListener();
    },

    onClick: function (event) {
        this.showErrorMessage(false);
        switch (event.target.data) {
            case "avatarUpload":
                var node = event.target.parentNode.parentNode;
                UploadManager.uploadListener(node);
                break;
            case "signupPopup":
                addClass($id('login-popup'), "sign-up");
                break;
            case "loginPopup":
                removeClass($id('login-popup'), "sign-up");
                break;
            case "signup":
                if (!this.checkFormValidate()) {
                    this.showErrorMessage(true);
                    return;
                }
                var obj = xmlUtils.getValue($id("register-popup"));
                obj.userid = "";
                obj.avatarURL = obj.tagImage;
                obj.tagImage = null;
                var xmlDoc = xmlUtils.objToXML(obj, "account");
                this.createAccount(xmlDoc);
                break;
            case "login":
                if (!this.checkFormValidate(true)) {
                    this.showErrorMessage(true, "Invalid username or password");
                    return;
                }
                var obj = xmlUtils.getValue($id("signin-popup"));
                this.login(obj);
                break;
            case "closeLoginPopup":
                this.close();
            default:
                break;
        }
    },

    createAccount: function (xmlDoc) {
        var success = function (resp) {
            if (resp.querySelector("account").firstChild) {
                LoginPopup.close();
                $id('username-login').value = "";
                $id('password-login').value = "";
                $id("account-wrapper").children[1].remove()
                $id('account-wrapper').appendChild(xmlUtils.transformXSL(resp, "templates/account.xsl", null));
            } else {
                LoginPopup.showErrorMessage(true, "Failed to register new account!");
            }
        };

        var failure = function () {
        };

        ajax.post({
            url: "LoginServlet",
            xml: xmlDoc,
            param: {action: "signup"},
            success: success,
            failure: failure
        });
    },

    checkUsername: function (username) {
        var success = function (resp) {
            var result = resp.querySelector("result").firstChild.nodeValue;
            result = result !== "false" ? true : false;
            inputValidated = result;
            LoginPopup.checkValidate($id('username-input'), result);
        };

        var failure = function () {
        };

        ajax.post({
            url: "LoginServlet",
            param: {action: "checkusername", username: username},
            success: success,
            failure: failure
        });
    },

    login: function (obj) {
        var success = function (resp) {
            if (resp && resp.querySelector("account").firstChild) {
                LoginPopup.close();
                $id('username-login').value = "";
                $id('password-login').value = "";
                $id("account-wrapper").children[1].remove();
                $id('account-wrapper').appendChild(xmlUtils.transformXSL(resp, "templates/account.xsl", null));
                if (LoginPopup.isCreate) {
                    window.location = "upload_image.jsp";
                }

                if (MainPage.isVisible) {
                    MainPage.getListLooks();
                } else if (LookDetail.isVisible) {
                    if ($class("username")[0]) {
                        $class("new-comment")[0].getElementsByTagName("img")[0].src = $class("account-wrappper")[0].getElementsByTagName("img")[0].src;
                    }
                }
            } else {
                LoginPopup.showErrorMessage(true, "Invalid username or password!");
            }
        };

        var failure = function () {

        };

        ajax.post({
            url: "LoginServlet",
            param: {action: "login", username: obj.usernameLogin, password: obj.passwordLogin},
            success: success,
            failure: failure
        });
    },

    initListener: function () {
        var listener = function (event) {
            if (this.id === "username-input") {
                if (!this.value || this.value.indexOf(" ") >= 0) {
                    LoginPopup.checkValidate(this);
                } else {
                    LoginPopup.checkUsername(this.value);
                }
            }
            else {
                var result = LoginPopup.validateEmail(this.value);
                inputValidated = result;
                LoginPopup.checkValidate(this, result);
            }
        };
        $id('username-input').removeEventListener('blur', listener, false);
        $id('username-input').addEventListener('blur', listener, false);
        $id('email-input').removeEventListener('blur', listener, false);
        $id('email-input').addEventListener('blur', listener, false);
    },

    validateEmail: function (email) {
        var regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return regex.test(email);
    },

    checkValidate: function (node, isSuccess) {
        if (!isSuccess) {
            removeClass(node, "success");
            addClass(node, "error");
        } else {
            removeClass(node, "error");
            addClass(node, "success");
        }
    },

    checkFormValidate: function (isLogin) {
        validate = true;
        if (isLogin) {
            if (hasClass($id('username-login'), "error") || !$id('username-login').value)
                return validate = false;

            if (hasClass($id('password-login'), "error") || !$id('password-login').value)
                return validate = false;
        } else {
            if (hasClass($id('username-input'), "error") || !$id('username-input').value)
                return validate = false;

            if (hasClass($id('email-input'), "error") || !$id('email-input').value)
                return validate = false;

            if (hasClass($id('password-input'), "error") || !$id('email-input').value)
                return validate = false;
        }
        return validate;
    },

    showErrorMessage: function (isShow, msg) {
        if (isShow) {
            removeClass($id('error-msg'), "hidden");
        } else {
            addClass($id('error-msg'), "hidden");
        }

        msg = msg ? msg : defaultMessage;
        $id('error-msg').innerText = msg;
    },

    show: function () {
        removeClass($id('popup'), "hidden");
        this.listener = function (event) {
            var node = event.target;
            event.target.data = xmlUtils.getNodeWithData(node);
            LoginPopup.onClick(event);
        };
        $id("login-popup").addEventListener("click", this.listener, false);
    },

    close: function () {
        addClass($id('popup'), "hidden");
        $id("login-popup").removeEventListener("click", this.listener);
    }

};

